'use strict';
const ERRCODE = require('../lib/errcode');

module.exports = {
  get ERRCODE() {
    if (!this[ERRCODE]) {
      this[ERRCODE] = ERRCODE;
    }
    return this[ERRCODE];
  },


  async erpGet(api, query = {}) {
    if (!this.__token__) {
      await this.initToken();
    }
    const url = `${this.config.erp.baseUrl}/api/get?url=${api}`;
    const obj = Object.assign({}, query, {
      'access-token': this.__token__,
      'secret-key': this.config.erp.secret_key,
    });
    const result = await this.curl(url, {
      method: 'POST',
      data: obj,
      dataType: 'json',
      // 5 秒超时
      timeout: this.config.erp.timeout || 5000,
    });
    return result.data;
  },

  async erpPost(api, data = {}) {
    if (!this.__token__) {
      await this.initToken();
    }
    const url = `${this.config.erp.baseUrl}/api/post?url=${api}`;
    const obj = Object.assign({}, data, {
      'access-token': this.__token__,
      'secret-key': this.config.erp.secret_key,
    });
    const result = await this.curl(url, {
      method: 'POST',
      data: obj,
      dataType: 'json',
      // 3 秒超时
      timeout: this.config.erp.timeout || 3000,
    });
    return result.data;
  },

  async initToken() {
    const url = this.config.erp.baseUrl + '/api/post?url=appToken';
    const result = await this.curl(url, {
      method: 'POST',
      data: {
        code: this.config.erp.code,
        secret_key: this.config.erp.secret_key,
      },
      contentType: 'form',
      dataType: 'json',
      // 3 秒超时
      timeout: 3000,
    });
    const timeout = this.config.erp.tokenTimeout || 24 * 3600 * 1000;
    this.__token__ = result.data.access_token;
    setTimeout(() => {
      this.__token__ = null;
    }, timeout);
  },

};
